package org.travel.travel2gether.service;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.travel.travel2gether.dao.AccountDao;
import org.travel.travel2gether.domain.Account;
import org.travel.travel2gether.domain.Role;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

@Service
public class FacebookService {
	
	@Value("${facebook.clientId}")
	private String CLIENT_ID;
	@Value("${facebook.clientSecret}")
	private String CLIENT_SECRET;
	@Value("${application.path}")
	private String APP_PATH;
	private String AUTH_CONTEXT = "/facebookAuthentication";

	@Autowired
	private UserService userService;
	
	@Autowired
	private AccountDao accountDao;
	
	public String getLoginRedirectURL() {
		String url = "https://www.facebook.com/dialog/oauth/?"
				+ "client_id=" + CLIENT_ID
				+ "&redirect_uri=" + APP_PATH + AUTH_CONTEXT
				+ "&scope=email,publish_stream,user_about_me,friends_about_me"
				+ "&state=" + "justtotestfbresponseafterlogin"
				+ "&display=page" + "&response_type=code";
		return url;
	}
	
	public void authenticate(String code) throws ClientProtocolException, IOException {
		String url = "https://graph.facebook.com/oauth/access_token?"
				+ "client_id=" + CLIENT_ID + "&redirect_uri=" + APP_PATH + AUTH_CONTEXT
				+ "&client_secret=" + CLIENT_SECRET + "&code=" + code;
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		String responseBody = httpclient.execute(httpget, new BasicResponseHandler());
		
		//extract access_token from response
		if (responseBody.contains("access_token")) {
			// success
			String[] mainResponseArray = responseBody.split("&");
			// {"access_token= AAADD1QFhDlwBADrKkn87ZABAz6ZCBQZ//DZD ","expires=5178320"}
			String accesstoken = "";
			for (String string : mainResponseArray) {
				if (string.contains("access_token")) {
					accesstoken = string.replace("access_token=", "").trim();
				}
			}
			FacebookClient facebookClient = new DefaultFacebookClient(accesstoken);
			User user = facebookClient.fetchObject("me", User.class);
			
			Account account = accountDao.findByFacebookId(user.getId());
			if(account == null) {
				account = new Account();
				account.setFacebookAccount(true);
				account.setFacebookId(user.getId());
				account.setRole(Role.FACEBOOK);
			}
			updateAccountInfo(user, account);
			accountDao.save(account);
			userService.signin(account);
		}
	}

	private void updateAccountInfo(User user, Account account) {
		account.setUsername(user.getEmail());
		account.setFirstName(user.getFirstName());
		account.setMiddleName(user.getMiddleName());
		account.setLastName(user.getLastName());
		account.setFacebookLink(user.getLink());
	}
}
